package com.zz.yt.lib.login.delegate.login;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.whf.android.jar.app.Latte;
import com.zz.yt.lib.login.R;
import com.zz.yt.lib.login.constant.ISignListener;
import com.zz.yt.lib.login.constant.ISignUpListener;
import com.zz.yt.lib.login.delegate.login.base.BaseFingerDelegate;
import com.zz.yt.lib.ui.view.SelectImageView;


/**
 * 登录
 *
 * @author qf
 * @version 2020-1-03
 */
@SuppressLint("ClickableViewAccessibility")
public class SignInDelegate extends BaseFingerDelegate  implements View.OnTouchListener {


    private EditText idEditPassword;
    private Button loginSign;

    private ISignListener mSignListener = null;
    private ISignUpListener mSignUpListener = null;

    @Override
    public void onAttach(@NonNull Context activity) {
        super.onAttach(activity);
        //这里是类型转换，而不是判断
        if (activity instanceof ISignListener) {
            mSignListener = (ISignListener) activity;
        }
        if (activity instanceof ISignUpListener) {
            mSignUpListener = (ISignUpListener) activity;
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.hai_delegate_sign_in;
    }

    private void inBundle() {
        if (mSignListener != null) {
            Object launcher = mSignListener.setSignIn();
            if (launcher != null) {
                if (launcher instanceof Integer) {
                    getImageView(R.id.login_image_background)
                            .setImageResource((int) launcher);
                } else if (launcher instanceof View) {
                    View viewLauncher = (View) launcher;
                    RelativeLayout view = findViewById(R.id.login_layout_background);
                    ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
                            ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT);
                    viewLauncher.setLayoutParams(layoutParams);
                    view.addView(viewLauncher);
                }
            }
        }

        //设置是否保存登录信息
        final SelectImageView idImageSelect = findViewById(R.id.login_img_acc_pass);
        setImgSelect(idImageSelect);

        //注册
        boolean isSignUp = false;
        if (mSignUpListener != null) {
            isSignUp = mSignUpListener.isSignUp();
            mSignUpListener.setSignUpView(mRootView, getTextView(R.id.login_text_sign_up));
        }
        getTextView(R.id.login_text_sign_up).setVisibility(isSignUp ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        inBundle();
        initView();
        inGradePermission();
    }

    private void initView() {
        idEditPassword = getEditText(R.id.login_edit_password);
        loginSign = getButton(R.id.login_btn_sign_in);
        idEditPassword.addTextChangedListener(this);
        idEditPassword.setOnTouchListener(this);
        idEditPassword.setText(getPassword());

        getEditText(R.id.login_edit_phone).setText(getPhone());
        getEditText(R.id.login_edit_phone).setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                findViewById(R.id.login_view_phone).setBackgroundResource(R.color.colorAccent);
            } else {
                findViewById(R.id.login_view_phone).setBackgroundResource(R.color.dim_grey);
            }
        });
        if (mSignListener != null) {
            mSignListener.setSignInView(loginSign);
            //测试服务器
            TextView textDebug = getTextView(R.id.text_debug);
            if (textDebug != null) {
                textDebug.setVisibility(Latte.isSwitchingServices() ? View.VISIBLE : View.GONE);
                mSignListener.setServiceSport(textDebug);
            }
        }
    }

    @Override
    protected void onGrantedSuccess() {
        loginSign.setOnClickListener(view -> {
            if (isGranted()) {
                setInstallPermission();
                return;
            }
            if (mSignListener != null) {
                String phone = getEditText(R.id.login_edit_phone)
                        .getText()
                        .toString()
                        .trim();
                String password = getEditText(R.id.login_edit_password)
                        .getText()
                        .toString()
                        .trim();

                if (isPhone(phone) && isPassword(password)) {
                    mSignListener.onSignIn(phone, password);
                }
            }
        });
    }

    /**
     * EditText的drawableRight属性设置点击事件
     */
    @SuppressLint("ClickableViewAccessibility")
    public boolean onTouch(View v, MotionEvent event) {
        // 得到一个长度为4的数组，分别表示左上右下四张图片(0.1.2.3)
        Drawable drawable = getDrawables(2);
        //如果右边没有图片，不再处理
        if (drawable == null)
            return false;
        //如果不是按下事件，不再处理
        if (event.getAction() != MotionEvent.ACTION_UP)
            return false;
        if (event.getX() > idEditPassword.getWidth()
                - idEditPassword.getPaddingRight()
                - drawable.getIntrinsicWidth()) {
            inPassword();
        }
        return false;
    }

    public Drawable getDrawables(int i) {
        if (idEditPassword != null) {
            return idEditPassword.getCompoundDrawables()[i];
        }
        return null;
    }

    /**
     * 密码显示隐藏
     */
    protected void inPassword() {
        if (idEditPassword.isSelected()) {
            idEditPassword.setSelected(false);
            setRightImage(idEditPassword, R.drawable.login_ic_visibility_off);
            idEditPassword.setInputType(InputType.TYPE_CLASS_TEXT
                    | InputType.TYPE_TEXT_VARIATION_PASSWORD);
        } else {
            idEditPassword.setSelected(true);
            setRightImage(idEditPassword, R.drawable.login_ic_visibility_on);
            idEditPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }
        idEditPassword.setSelection(idEditPassword.getText().length());
    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (idEditPassword != null && loginSign != null) {
            loginSign.setEnabled(idEditPassword.getText().toString().trim().length() > 1);
        }
    }

}